//
//  RegisterCheckViewController.m
//  翼安保
//
//  Created by duzhi on 2024/4/28.
//

#import "RegisterCheckViewController.h"
#import "DetailListCell0.h"
#import "RegisterCheckApi.h"
#import "RegisterCheckModel.h"
#import "UserInfo.h"

@interface RegisterCheckViewController ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate,UISearchBarDelegate>
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *datas;
@end

@implementation RegisterCheckViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"注册审批";
    NewsBigButton *backButton = [NewsBigButton new];
    [backButton setBackgroundImage:[UIImage imageNamed:@"back_black_26x26"] forState:0];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    [self getAllDatas];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.navigationController.interactivePopGestureRecognizer.enabled=YES;
    self.navigationController.interactivePopGestureRecognizer.delegate=self;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)closeKB {
    [self.view endEditing:YES];
}

- (void)back {
    [self.navigationController popViewControllerAnimated:NO];
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

- (void)getAllDatas {
    id userInfoString =  [[NSUserDefaults standardUserDefaults] objectForKey:KUserInfo];
    if (!userInfoString) {
        return;
    }
    UserInfo *userInfo = [UserInfo mj_objectWithKeyValues:userInfoString];
    NSMutableDictionary *dic = [NSMutableDictionary new];
    dic[@"fManagerPhone"] = userInfo.phone;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[AFNNetWorkManager shareAFNNetWorkManager] Get:getCheckListByManagerPhone parameters:dic success:^(NSURLSessionDataTask *task, Result *result) {
        [hud hideAnimated:YES];
        if (result.code == 200) {
//            NSArray *tempDatas = @[@{@"fName":@"duzhi",@"fPhone":@"18795808522",@"fCompanyName":@"123"},@{@"fName":@"duzhi",@"fPhone":@"18795808522",@"fCompanyName":@"123"},@{@"fName":@"duzhi",@"fPhone":@"18795808522",@"fCompanyName":@"123"}];
//            NSMutableArray *datas = [RegisterCheckModel mj_objectArrayWithKeyValuesArray:tempDatas];
            NSMutableArray *datas = [RegisterCheckModel mj_objectArrayWithKeyValuesArray:result.data];
            if (!datas||datas.count==0) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [MBProgressHUD showTextHUD:@"暂无数据"];
                    [self.navigationController popViewControllerAnimated:YES];
                });
                return;
            }
            self.datas = datas;
            [self.tableView reloadData];
        }else {
            [MBProgressHUD showTextHUD:result.msg];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [hud hideAnimated:YES];
        [MBProgressHUD showTextHUD:@"请检查网络设置"];
    }];
}

- (void)getSearchDatas:(NSString *)phone {
    [self.view endEditing:YES];
    NSMutableDictionary *dic = [NSMutableDictionary new];
    dic[@"fPhone"] = phone;
    [[AFNNetWorkManager shareAFNNetWorkManager] Get:getCheckListByPhone parameters:dic success:^(NSURLSessionDataTask *task, Result *result) {
        if (result.code == 200) {
            RegisterCheckModel *model = [RegisterCheckModel mj_objectWithKeyValues:result.data];
            if (!model) {
                [MBProgressHUD showTextHUD:@"暂无数据"];
                return;
            }
            self.datas = @[model].mutableCopy;
            [self.tableView reloadData];
        }else {
            [MBProgressHUD showTextHUD:result.msg];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [MBProgressHUD showTextHUD:@"请检查网络设置"];
    }];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"%@",searchBar.text);
    if (searchBar.text.length == 0) {
        [self getAllDatas];
    }else {
        [self getSearchDatas:searchBar.text];
    }
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (searchText.length == 0) {
        [self getAllDatas];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.datas.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RegisterCheckModel *model = self.datas[indexPath.section];
    DetailListCell0 *cell = (DetailListCell0 *)[tableView dequeueReusableCellWithIdentifier:@"DetailListCell0" forIndexPath:indexPath];
    switch (indexPath.row) {
        case 0:
            [cell setTitle:@"姓名" desc:model.fName];
            break;
        case 1:
            [cell setTitle:@"手机号" desc:model.fPhone];
            break;
        case 2:
            [cell setTitle:@"公司名" desc:model.fCompanyName];
            break;
            
        default:
            break;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return relativeWidth(40);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [UIView new];
    UIColor *textColor = UIColorFromRGB(0x1296db);
    CGFloat fontSize   = relativeWidth(13);
    
    NewsBigButton *refuseButton = [NewsBigButton new];
    refuseButton.tag = section+10000;
    [refuseButton setTitle:@"拒绝" forState:0];
    refuseButton.titleLabel.font = [UIFont systemFontOfSize:fontSize];
    [refuseButton setTitleColor:textColor forState:0];
    [refuseButton addTarget:self action:@selector(refuseButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:refuseButton];
    [refuseButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(relativeWidth(20));
        make.centerY.mas_equalTo(0);
    }];
    
    NewsBigButton *agreeButton = [NewsBigButton new];
    agreeButton.tag = section+10000;
    agreeButton.titleLabel.font = [UIFont systemFontOfSize:fontSize];
    [agreeButton setTitle:@"通过" forState:0];
    [agreeButton setTitleColor:textColor forState:0];
    [agreeButton addTarget:self action:@selector(agreeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:agreeButton];
    [agreeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(refuseButton.mas_right).offset(relativeWidth(15));
        make.centerY.mas_equalTo(0);
    }];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return relativeWidth(30);
}

- (void)refuseButtonClick:(UIButton *)button {
    [self agreeOrRefuse:2 tag:button.tag];
}

- (void)agreeButtonClick:(UIButton *)button {
    [self agreeOrRefuse:1 tag:button.tag];
}

//type 1-同意 2-不同意
- (void)agreeOrRefuse:(int)type tag:(NSInteger)tag{
    RegisterCheckModel * model = self.datas[tag-10000];
    NSString *tipStr = type == 1?@"确定通过审批？":@"确定拒绝审批？";
    [self alertTitle:tipStr ok:^{
        NSMutableDictionary *dic = [NSMutableDictionary new];
        dic[@"fPhone"] = model.fPhone;
        dic[@"fState"] = [NSString stringWithFormat:@"%d",type];
        [[AFNNetWorkManager shareAFNNetWorkManager] Post:checkListAuditSubmit parameters:dic success:^(NSURLSessionDataTask *task, Result *result) {
            if (result.code == 200) {
                [self.datas removeObject:model];
                if (self.datas.count == 0) {
                    [self.navigationController popViewControllerAnimated:YES];
                }else{
                    [self.tableView reloadData];
                }
                [MBProgressHUD showTextHUD:@"操作成功"];
            }else {
                [MBProgressHUD showTextHUD:result.msg];
            }
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            [MBProgressHUD showTextHUD:@"请检查网络设置"];
        }];
    }];
}

- (void)alertTitle:(NSString *)title ok:(void(^)(void))okBlock {
    UIAlertController *alertview = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *left = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    UIAlertAction *right = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (okBlock) {
            okBlock();
        }
    }];
    [alertview addAction:left];
    [alertview addAction:right];
    [self presentViewController:alertview animated:YES completion:nil];
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 1) style:UITableViewStyleInsetGrouped];
        _tableView .delegate = self;
        _tableView .dataSource = self;
        _tableView .estimatedRowHeight = 0;
        _tableView .separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        _tableView .showsVerticalScrollIndicator = NO;
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, kiPhoneX_Bottom_Height, 0);
        [_tableView registerClass:[DetailListCell0 class] forCellReuseIdentifier:@"DetailListCell0"];
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.bottom.mas_equalTo(0);
        }];
        
        UIView *headerView = [UIView new];
        headerView.frame = CGRectMake(0, relativeWidth(20), ScreenWidth-relativeWidth(20)*2, relativeWidth(76));
        _tableView.tableHeaderView = headerView;
        
        UIView *searchContentView = [UIView new];
        searchContentView.frame = CGRectMake(relativeWidth(10), relativeWidth(20), ScreenWidth-relativeWidth(10)*2, relativeWidth(36));
        [headerView addSubview:searchContentView];
        // 创建并配置UISearchBar
        UISearchBar *searchBar = [[UISearchBar alloc] init];
        searchBar.searchBarStyle = UISearchBarStyleMinimal;
        searchBar.frame = CGRectMake(0, 0, ScreenWidth-relativeWidth(10)*2, relativeWidth(36));
        searchBar.delegate = self;
        searchBar.placeholder = @"请输入注册者手机号";
        [searchContentView addSubview:searchBar];
        
        
        UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
        UIBarButtonItem * space1 =[[UIBarButtonItem alloc]initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(closeKB)];
        toolBar.items = @[space1,right];
        searchBar.inputAccessoryView = toolBar;
        
//        UIButton *closeButton = [UIButton new];
//        [closeButton setTitle:@"完成" forState:0];
//        [closeButton setTitleColor:UIColorFromRGB(0x1296db) forState:0];
//        [closeButton addTarget:self action:@selector(closeKB) forControlEvents:UIControlEventTouchUpInside];
//        searchBar.inputAccessoryView = closeButton;
        
    }
    return _tableView;
}

@end
